package com.beyondsoft.mcms.web;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.domain.Users;

@RequestMapping("/changepwd/**")
@Controller
public class ChangePwdController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(Model uiModel, HttpServletRequest request) {
    	String oldPassword = request.getParameter("oldPassword");
    	String newPassword = request.getParameter("newPassword");
    	String confirmPassword = request.getParameter("confirmPassword");
    	
    	Users user = CommonUtils.getCurrentUser();
    	String userPassword = user.getPassword();
    	if (! userPassword.equals(CommonUtils.encodingPWD(oldPassword))){
    		uiModel.addAttribute("backMessage", "changepwd_oldpassword_error");
    		return "changepwd/index";
    	}
    	
    	if (! newPassword.equals(confirmPassword)){
    		uiModel.addAttribute("backMessage", "changepwd_confirmpassword_error");
    		return "changepwd/index";
    	}
    	
    	user.setPassword(CommonUtils.encodingPWD(newPassword));
    	user.merge();
    	
    	uiModel.addAttribute("backMessage", "changepwd_success");
        return "changepwd/index";
    }

    @RequestMapping
    public String index() {
        return "changepwd/index";
    }
}
